#!/bin/bash

# This script is run during "git commit" before the commit message editor
# is shown.
#
# It automatically adds a BUG=<bug number> line to the default commit
# message if the branch name starts with "b<bug number>".
# Note that <bug number> refers to a Google internal bug number.

branch="$(git rev-parse --abbrev-ref HEAD)"
# Examples: 28221285, b28221285, 28221285_feature, b28221285_feature
if [[ "$branch" =~ ^b?([0-9]{8,}) ]]; then
  bug=${BASH_REMATCH[1]}
fi

if [[ -z "$bug" ]]; then
  # No bug found in branch name. Exit early.
  exit 0
fi

bug_marker_line="BUG=$bug"
bug_url="b/${bug}"

# Check current commit message (e.g. in case of an --amend).
msg_file="$1"
if grep -q "$bug_marker_line" "$msg_file"; then
  exit 0
fi

# Check other commits in the branch as well.
if [[ -n "$(git log --no-merges -E --grep="^$bug_marker_line$|$bug_url" master..)" ]]; then
  echo "Note: Bug number found in branch name ($bug) but not adding it to this commit message because previous commits already include it."
  exit 0
fi

# Add the bug number to the commit message.
type="$2"
# TODO(mberlin): React on other types as well?
# https://git-scm.com/docs/githooks lists these types:
# template, merge, squash
if [[ -z "$type" || "$type" == "commit" || "$type" == "message" ]]; then
  echo >> "$msg_file"
  echo "$bug_marker_line" >> "$msg_file"
fi
